package cn.timeapi.Applet.Mall.CatSquare.controller.portal;

import cn.timeapi.Applet.Mall.CatSquare.common.*;
import cn.timeapi.Applet.Mall.CatSquare.config.SystemConfig;
import cn.timeapi.Applet.Mall.CatSquare.service.ILogin;
import cn.timeapi.Applet.Mall.CatSquare.dao.AccountMapper;
import cn.timeapi.Applet.Mall.CatSquare.entity.Account;
import cn.timeapi.Applet.Mall.CatSquare.model.WXSessionModel;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import static com.alibaba.druid.sql.dialect.mysql.ast.clause.MySqlFormatName.JSON;
//import cn.timeapi.Applet.Mall.CatSquare.common.RedisOperator;


/**
 * @description: 小程序账号接口
 * @author: Vincent Vic
 * @email: vincent-vic@qq.com
 * @time: 2020/9/28 20:33
 */
@Api("account")
@RestController
@RequestMapping("/Account/")   //请求地址设置
public class AccountController {

	private static Logger log = LoggerFactory.getLogger(AccountController.class);

	@Autowired
	private RedisOperator<String,Account> redis;

	@Autowired
	private RedisOperator<String,String> registerRedis;



	@Autowired
	private ILogin iLogin;

	@Autowired
	private AccountMapper accountMapper;

	/**
	 * 微信登入 成功返回用户信息，不成功返回不成功状态信息
	 * @param code
	 * @return
	 */
	@ApiOperation("微信登入 成功返回用户信息，不成功返回不成功状态信息")
	@GetMapping("wxLogin")
	public ServerResponse wxLogin(@ApiParam("随机码") @ParamsNotNull String code) {

		log.debug("wxlogin - code: " + code);
		ServerResponse<WXSessionModel> serverResponse = iLogin.wxLogin(code);
		Account account = null ;
		String openId = serverResponse.getData().getOpenid();
		String sessionKey = serverResponse.getData().getSession_key();
		if (serverResponse.isSuccess()){
			account = accountMapper.selectByOpenId(serverResponse.getData().getOpenid());
			log.debug(account.toString());
			if (account == null){
				registerRedis.set(Const.REDIS_LOGIN_PREFIX + sessionKey,openId);
				return ServerResponse.build(204,"跳转注册",serverResponse.getData());
			} else {

				log.debug("session_key  ==>  "+serverResponse.getData().getSession_key());


				String redisLoginKey = DigestUtils.md5Hex(sessionKey.getBytes());
				redis.set(Const.REDIS_LOGIN_PREFIX + redisLoginKey ,account, SystemConfig.LoginTimeout);
				account.setOpenId(redisLoginKey);
				return ServerResponse.success(account);
			}
		}
		System.out.println("json: "+JSONObject.toJSON(serverResponse));
		return serverResponse;
	}

	/**
	 * 微信登入 成功返回用户信息，不成功返回不成功状态信息
	 * @param sessionKey
	 * @return
	 */
	@ApiOperation("微信登出")
	@GetMapping("wxLogout")
	public ServerResponse wxLogout(@ApiParam("会话码") @ParamsNotNull String sessionKey) {
		log.debug("wxLogout - sessionKey: " + sessionKey);
		boolean flag = redis.del(Const.REDIS_LOGIN_PREFIX + sessionKey);
		if (!flag){
			ServerResponse.errorTokenMsg("退出失败");
		}

		return ServerResponse.success("成功退出登入");
	}

	/**
	 * 用户注册
	 * @param account
	 * @return
	 */
	@ApiOperation("微信注册")
	@GetMapping("register")
	public ServerResponse register(@ApiParam("会话码") @ParamsNotNull String sessionKey, @ApiParam("用户信息") Account account) {
		//判断是否已经存在
		if (isAccount(sessionKey).isSuccess()) {
			return ServerResponse.errorMsg("用户已存在");
		}else {
			String openId = registerRedis.get(Const.REDIS_LOGIN_PREFIX + sessionKey);
			account.setOpenId(openId);
			int res = accountMapper.insertSelective(account);
			if (res == 0){
				return ServerResponse.errorTokenMsg("注册失败");
			} else {
				redis.set(Const.REDIS_LOGIN_PREFIX + sessionKey,account,SystemConfig.LoginTimeout);
				account.setOpenId(sessionKey);
				return ServerResponse.success(account);
			}
		}
	}

	/**
	 * 用户注册
	 * @param account
	 * @return
	 */
	@ApiOperation("微信更新")
	@GetMapping("update")
	public ServerResponse update(@ApiParam("会话码") @ParamsNotNull String sessionKey, @ApiParam("用户属性") Account account) {

		System.out.println(account);
		//判断是否登入
		Account acc = redis.get(Const.REDIS_LOGIN_PREFIX + sessionKey);
		if (acc == null){
			return ServerResponse.error(ResponseCode.NEED_LOGIN.getCode(),"未登录，需要登录");
		}
		//将sessionKey 改成 openId
		account.setOpenId(acc.getOpenId());
		//判断是否已经存在
		if (isAccount(account.getOpenId()).isSuccess() && accountMapper.updateByOpenIdSelective(account) != 0) {
			redis.set(Const.REDIS_LOGIN_PREFIX + sessionKey,account,SystemConfig.LoginTimeout);
			return ServerResponse.success("更新成功");
		}
		return ServerResponse.errorTokenMsg("更新失败");
	}

	/**
	 * 获取用户信息
	 * @param sessionKey
	 * @return
	 */
	@ApiOperation("微信用户信息获取")
	@GetMapping("getInfo")
	public ServerResponse getInformation( @ApiParam("会话码") @ParamsNotNull String sessionKey) {
		Account account = redis.get(Const.REDIS_LOGIN_PREFIX + sessionKey);
		if (account == null){
			return ServerResponse.error(ResponseCode.NEED_LOGIN.getCode(),"未登录，需要登录");
		}
		account.setOpenId(sessionKey);
		return ServerResponse.success(account);
	}

	/**
	 * 微信登入 成功返回用户信息，不成功返回不成功状态信息
	 * @param sessionKey
	 * @returns
	 */
	@ApiOperation("微信用户信息状态")
	@GetMapping("isAccount")
	@ResponseBody   //自动序列化Json
	public ServerResponse isAccount(@ParamsNotNull @ApiParam("会话码") String sessionKey) {

		log.debug("isAccount - sessionKey: " + sessionKey);

		Account account = redis.get(Const.REDIS_LOGIN_PREFIX + sessionKey);
		if (account == null){
			return ServerResponse.error(Constant.NEED_REGISTER.getCode(),"未登录，需要登录");
		}
		return ServerResponse.success("已注册");

	}

}
